package controller

import (
	"jtvss/api/system/dto"
	"jtvss/api/system/model"
	"jtvss/middleware"
	"jtvss/pkg/ctx"
	"jtvss/pkg/orm"
	"jtvss/util"

	"github.com/gin-gonic/gin"
)

// Role
type Role struct {
}

// PageHandler 列表
func (o *Role) PageHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	tok := middleware.UserToken(c)
	if tok.RoleID != model.SysUserRoleID {
		p.CreatedBy = tok.UserName
	}
	var data []model.Role
	total, _ := p.DbModelWhere(&model.Role{}).Find(&data)
	ctx.JSONWriteTotal(total, data, c)
}

// GetHandler 查询
func (o *Role) GetHandler(c *gin.Context) {
	util.QueryByID(&model.Role{}, c)
}

// GetRolePowerHandler 查询
func (o *Role) GetRolePowerHandler(c *gin.Context) {
	getId, err := ctx.QueryUInt(c, "roleId")
	if err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	var p model.Role
	if err := orm.DbFirstByID(&p, getId); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	locRoleId := middleware.UserToken(c).RoleID
	var menus []model.Menu
	if locRoleId != model.SysUserRoleID {
		var locRole model.Role
		if err := orm.DbFirstByID(&locRole, locRoleId); err != nil {
			ctx.JSONWriteError(err, c)
			return
		}
		orm.DbFindBy(&menus, "ID in (?)", locRole.MenuIds)
	} else {
		orm.DbFind(&menus)
	}
	// roles 查询用户权限 menus当前登录用户全面
	ctx.JSONWriteData(gin.H{"menuIds": p.MenuIds, "menus": menus}, c)
}

// AddHandler 新增
func (o *Role) AddHandler(c *gin.Context) {
	var p model.Role
	//获取参数
	if err := c.ShouldBind(&p.RoleOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbCreate(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateHandler 修改
func (o *Role) UpdateHandler(c *gin.Context) {
	var p model.Role
	if err := c.ShouldBind(&p.RoleOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	// 更新数据
	if err := orm.DbUpdateModelByID(&p, p.ID); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// EnableHandler 改变状态
func (o *Role) EnableHandler(c *gin.Context) {
	var p model.Role
	//获取参数
	if err := c.ShouldBind(&p.RoleOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateByID(&model.Role{}, p.ID, orm.H{"Enable": p.Enable}); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 删除
func (o *Role) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.Role{}, c)
}

func (o Role) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.GET("/getRolePower", o.GetRolePowerHandler)
	r.PUT("/enable", o.EnableHandler)
	r.PUT("", o.UpdateHandler)
	r.DELETE("/:id", o.DeleteHandler)
}
